package com.example.model;

import lombok.Data;

import java.io.Serializable;

/**
 * @author hello
 * @date 2023-04-13 17:34:20
 */
@Data
public class ApiResponse<T> implements Serializable {

    private static final int STATUS_500 = 500;
    public static final int SUCCESS_CODE = 200;
    private static final String SUCCESS_MSG = "success";
    private static final String ERROR_MSG = "服务端异常";
    private Integer code;
    private String msg;
    private T data;

    public ApiResponse(Integer code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public ApiResponse() {
    }

    /**
     * 成功
     */
    public static <T> ApiResponse<T> ok() {
        return restResult(null, SUCCESS_CODE, SUCCESS_MSG);
    }

    public static <T> ApiResponse<T> ok(T data) {
        return restResult(data, SUCCESS_CODE, SUCCESS_MSG);
    }

    public static <T> ApiResponse<T> ok(T data, String msg) {
        return restResult(data, SUCCESS_CODE, msg);
    }


    /**
     * 错误
     */
    public static <T> ApiResponse<T> error() {
        return restResult(null, STATUS_500, ERROR_MSG);
    }


    public static <T> ApiResponse<T> error(String msg) {
        return restResult(null, STATUS_500, msg);
    }

    public static <T> ApiResponse<T> error(T data) {
        return restResult(data, STATUS_500, ERROR_MSG);
    }

    public static <T> ApiResponse<T> error(T data, String msg) {
        return restResult(data, STATUS_500, msg);
    }

    public static <T> ApiResponse<T> error(int code, String msg) {
        return restResult(null, code, msg);
    }

    private static <T> ApiResponse<T> restResult(T data, int code, String msg) {
        ApiResponse<T> apiResult = new ApiResponse<>();
        apiResult.setCode(code);
        apiResult.setData(data);
        apiResult.setMsg(msg);
        return apiResult;
    }
}
